/*
 * @Author: chunlai
 * @Date: 2025-07-14 13:39:39
 * @LastEditTime: 2025-09-09 11:32:12
 * @LastEditors: minsheng_insurance_agency_zhoucl
 * @FilePath: \02.bldinsure\src\store\modules\json.js
 * @Description: 获取json配置
 */
import $http from "@/utils/request";
import consts from "@/config/const.js";
import { getDataFromUrl } from "@/utils/";
const version = require("@/config/version.json");
const json_ver = `${JSON_VERSION || version.version}`;

const state = {
  insu3Status: "", // 安盛订单状态判断(页面是否可修改)
  netAssessQues: [],
  areaCodes: [],
  postCodes: {},
  /**请求开关*/
  postJsonConfig:"0",
  insureJsonConfig: "0",
};
const getters = {
  insu3Status: (state) => state.insu3Status,
  netAssessQues: (state) => state.netAssessQues,
};
const mutations = {
  SET_STATE_FIELD(state, payload) {
    Object.assign(state, payload);
  },
  SET_AS_BILL_STATUS(state, payload) {
    state.insu3Status = payload;
  },
  SET_NET_ASSESS_QUES(state, data) {
    state.netAssessQues = data;
  },
  SET_AREA_CODE(state, data) {
    state.areaCodes = data;
  },
  SET_POST_CODES(state, data) {
    state.postCodes = data;
  },
};
const resetAreaCodes = (list) => {
  list.forEach((item) => {
    item.defaultIndex = 0;
    if (item.children) {
      if (item.children.length == 0) {
        delete item.children;
      } else {
        resetAreaCodes(item.children);
      }
    }
  });
  return list;
};
const getJsonNameUrl = (fileName) => {
  let baseUrl = consts.baseDomain;
  if (process.env.VUE_APP_PRODFLAG == "wxsc") {
    baseUrl = consts.baseWxscDomain;
  }
  return `${baseUrl}/dataModules/${getDataFromUrl(
    "company"
  )}/${fileName}.json?v=${json_ver}`;
};
// ,{root: true}
const actions = {
  getJson9Config({ commit, dispatch }, jsonName) {
    return new Promise((resolve, reject) => {
      const json_ver = `${JSON_VERSION || version.version}`;
      $http
        .get(
          `//wxou.mschn.cn/app_h5/insurepics/jsons/${jsonName}.json?v=${json_ver}`,
          {
            baseURL: "",
          }
        )
        .then((res) => {
          resolve(res);
        });
    });
  },
  getPageConfig({ commit, dispatch }) {
    return new Promise((resolve, reject) => {
      $http
        .get(getJsonNameUrl("page"), {
          baseURL: "",
        })
        .then((res) => {
          let { inputReg = {}, comQuestions = {}, ...pageState } = res;
          if (inputReg) {
            dispatch("infoReg/initInfoStore", inputReg, { root: true });
          }
          if (comQuestions) {
            commit("home/SET_COM_QUES", comQuestions, { root: true });
          }
          dispatch("page/initPageConfig", pageState, { root: true });
          resolve(res);
        });
    });
  },
  getDictConfig({ commit, dispatch }) {
    return new Promise((resolve, reject) => {
      $http
        .get(getJsonNameUrl("dictionary"), {
          baseURL: "",
        })
        .then((res) => {
          // 非正式环境,证件照不OCR识别
          if (process.env.VUE_APP_PRODFLAG !== "wxou") {
            commit(
              "dictionary/INIT_DATA",
              {
                noneOcrCheckIdCard: true,
              },
              { root: true }
            );
          }
          if (consts.object(res) && Object.keys(res).length > 0) {
            dispatch("dictionary/initDictionaryCode", res, { root: true });
          }
          resolve(res);
          dispatch("otherJsons");
        });
    });
  },
  getHealthyJson({ rootGetters, commit }) {
    return new Promise((resolve, reject) => {
      commit("updateLoad", true, { root: true });
      let jsonName = "healthy";
      const noticeCfg = rootGetters["page/riskRelateNotice"];
      const mainCode = rootGetters["insert/mainRiskCode"];
      const fdObj = noticeCfg.find((ele) => ele.code.includes(mainCode));
      if (fdObj) {
        jsonName = fdObj.name;
      }
      $http
        .get(getJsonNameUrl(jsonName), {
          baseURL: "",
        })
        .then((res) => {
          resolve(res);
          commit("updateLoad", false, { root: true });
        })
        .finally((err) => {
          commit("updateLoad", false, {
            root: true,
          });
        });
    });
  },
  toApplyDaKuan({ commit, dispatch, rootGetters }) {
    return new Promise((resolve, reject) => {
      commit("updateLoad", true, { root: true });
      const workNum = rootGetters["insert/workNum"],
        bldUserId = rootGetters["insert/bldUserId"],
        totalPrem = rootGetters["insert/totalPrem"];
      $http
        .post(
          "/ms-insure/api/bilaiduo/applyDaKuan",
          {
            workNum: workNum,
            userId: bldUserId,
            money: totalPrem,
          },
          {
            json: true,
          }
        )
        .then((res) => {
          resolve(res);
          commit("updateLoad", false, { root: true });
        })
        .finally((err) => {
          commit("updateLoad", false, {
            root: true,
          });
        });
    });
  },
  otherJsons({ state, commit, dispatch }) {
    if (state.insureJsonConfig == "0") {
      dispatch("getJson9Config", "insure").then((res) => {
        commit("SET_STATE_FIELD", {
          insureJsonConfig: "1",
        });
        if (Object.keys(res).length > 0) {
          commit("page/SET_FIELD_DESC_CFG", res, { root: true });
        }
      });
    }
    if(state.postJsonConfig == '0'){
      dispatch("getJson9Config", "postcode").then((res) => {
        commit("SET_STATE_FIELD", {
          postJsonConfig: "1",
        });
        if (Object.keys(res).length > 0) {
          commit("SET_POST_CODES", res);
        }
      });
    }
    if (state.areaCodes.length === 0) {
      $http
        .get(getJsonNameUrl("area"), {
          baseURL: "",
        })
        .then((res) => {
          if (res && res.addressData) {
            commit("SET_AREA_CODE", res.addressData);
          }
        });
    }
  },
  getNoticeJson({ commit, rootState, rootGetters }, jname = "") {
    return new Promise((resolve, reject) => {
      commit("updateLoad", true, { root: true });
      let jsonName = "";
      if (jname) {
        jsonName = jname;
      } else {
        jsonName = "healthy";
        const checkedRisks = rootGetters["risks/showedRisks"],
          relates = rootGetters["page/riskRelateNotice"],
          mainCode = rootGetters["insert/mainRiskCode"];
        /**
         * 百年告知版本要求(2022-3-17)
         * 1913、1914、1915、1916单主险,
         * 或者如果搭配“5031附加医惠通； 5904附加安康保； 5908附加康佑保；3901附加康睿保”中一个或几个附加险时，使用特殊告知19138版本，
         * 含有非指定附加险,则用普通告知
         */
        const cache2 = rootState.page?.healthVersion || {};
        if (cache2.main && cache2.main.includes(mainCode)) {
          jsonName = "healthy19138";
          const findArr2 =
            checkedRisks.filter(
              (ele) => !cache2.subrisk.includes(ele.varietyCode)
            ) || [];
          // 不是单主险,且含有非指定附加险
          if (findArr2.length > 1) {
            jsonName = "healthy";
          }
        }
        // 特殊产品配置不同告知(长城)
        if (relates.length > 0) {
          const fdObj = relates.find((ele) => ele.code.includes(mainCode));
          if (fdObj) {
            jsonName = fdObj.name;
            // healthy00363_60631  60631险种需要传告知(长城00363)
            // 附加险都是全健告(保司确认,2023-10-30)
            // 一个产品,多版本告知配置multi
            if (fdObj.multi && fdObj.multi == "1") {
              const fndFuJia = checkedRisks.length > 1;
              if (fndFuJia) {
                jsonName = "healthy00363_60631";
              }
            }
          }
        }
      }
      $http
        .get(getJsonNameUrl(jsonName), {
          baseURL: "",
        })
        .then((res) => {
          // console.log(`getNoticeJson---${jsonName}`, res);
          res.jsonName = jsonName;
          resolve(res);
          commit("updateLoad", false, { root: true });
        })
        .finally((err) => {
          commit("updateLoad", false, {
            root: true,
          });
        });
    });
  },
  getAreaJson({ state, commit }, type = "1") {
    return new Promise(async (resolve, reject) => {
      commit("updateLoad", true, { root: true });
      let list = [];
      if (state.areaCodes.length === 0) {
        let res = await $http.get(getJsonNameUrl("area"), {
          baseURL: "",
        });
        if (res && res.addressData) {
          commit("SET_AREA_CODE", res.addressData);
          list = res.addressData;
        }
      } else {
        list = JSON.parse(JSON.stringify(state.areaCodes));
      }
      let data = [];
      if (type == "2") {
        data = list.map((item) => {
          item.text = item.label;
          item.children.forEach((city) => {
            city.text = city.label;
            delete city.children;
          });
          return item;
        });
      } else if (type == "1") {
        data = resetAreaCodes(list);
      } else {
        data = list;
      }
      // console.log("getAreaJson", data);
      resolve(data);
      commit("updateLoad", false, { root: true });
    });
  },
  getJson3Config({ commit }, fileName) {
    return new Promise((resolve, reject) => {
      $http
        .get(getJsonNameUrl(fileName), {
          baseURL: "",
        })
        .then((res) => {
          resolve(res);
        });
    });
  },
};

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions,
};
